package tools

import (
	"fmt"
	"github.com/shirou/gopsutil/process"
	"strings"
)

func ShowProccessConnection(p *process.Process) {
	connects, _ := p.Connections()
	for _, c := range connects {
		// 连接类型
		connectType := ""
		if c.Type == 1 {
			connectType = "TCP"
		}
		if c.Type == 2 {
			connectType = "UDP"
		}

		// 本地地址
		laddr := fmt.Sprintf("%s:%d", c.Laddr.IP, c.Laddr.Port)

		// 对端地址
		raddr := ""
		if c.Raddr.Port != 0 {
			raddr = fmt.Sprintf("->%s:%d", c.Raddr.IP, c.Raddr.Port)

		}
		Out(ItemPrefix, connectType, laddr, raddr, c.Status)

	}

}

func ShowProcess(args []string) (err error) {
	// 获取参数
	optionName := ""
	if len(args) == 2 {
		optionName = args[1]
	}

	// 获取所有在运行的进程
	parr, err := process.Processes()
	if err != nil {
		return err
	}

	// 遍历
	for _, p := range parr {
		name, _ := p.Name()
		id := p.Pid

		if optionName == "" {
			// 没有过滤条件
			FmtOut("%s%s(pid=%d)\n", Prefix, name, id)
			ShowProccessConnection(p)
		} else {
			// 有过滤条件
			lowerName := strings.ToLower(name)
			if strings.Contains(lowerName, optionName) {
				FmtOut("%s%s(pid=%d)\n", Prefix, name, id)
				ShowProccessConnection(p)
			}
		}
	}
	return nil
}

func ProcessTool() *Option {
	return &Option{"pls", ShowProcess, "pls [processName] 查看指定或所有进程网络通信状态."}
}
